<template>
    <component is="a-modal" v-model:visible="visible" width="90%" :title="title" :mask-closable="false"
        :ok-loading="loading" @cancel="close" @before-ok="submit" :ok-text="'提交'" :titleAlign="'start'">
        <template #title>
            <div style="display: flex;align-items: center;justify-content: space-between;width: 100%;">
                <a-space>
                    <a-input placeholder="key" style="width: 300px;" v-model="searchForm.keyword" allow-clear></a-input>
                    <a-button type="primary" @click="search"><icon-search /> 搜索</a-button>
                    <a-button type="primary" @click="addKey"><icon-plus /> 添加key</a-button>
                    <a-upload action="/" accept=".xlsx,.xls" :limit="0" v-model:file-list="fileList" :auto-upload="false" :show-file-list="false" @change="uploadExcel">
                        <template #upload-button>
                            <a-button type="primary" style="background-color: #e18a3b;">
                                <icon-upload /> 导入Excel</a-button>
                        </template>
                    </a-upload>
                    <a-button type="primary" style="background-color:#1e90ff ;" @click="exportExcel"><icon-download />
                        下载Excel</a-button>
                    <a-button type="primary" @click="refreshSql" style="background-color: #ea5514;">
                        <icon-cloud-download />
                        数据库导入</a-button>
                </a-space>
                <div style="margin-right: 30px;">多语言编辑</div>
            </div>

        </template>
        <a-spin :loading="spinLoading" tip="数据加载中，请稍后···" style="width: 100%;height: 60vh;position: relative;">
            <a-scrollbar type="track" style="height:58vh;overflow: auto;" @scroll="handleScroll" ref="scrollRef">
                <a-table row-key="rowIndex" :sticky-header="0.5" :stripe="true" :data="currentPageData" ref="tableRef"
                    :pagination="false" class="table" style="width: 100%;height: 500px;">
                    <template #columns>
                        <a-table-column title="key" align="center" :width="200" :tooltip="true" :ellipsis="true">
                            <template #cell="{ record, column, rowIndex }">
                                <template v-if="record?.type == 'add'">
                                    <a-input @blur="getBlur(record.key)" v-model="record.key" placeholder="请输入key">
                                        <template #append>
                                            <icon-delete style="color:red;cursor: pointer;"
                                                @click="deleteColumn(rowIndex)" />
                                        </template>
                                    </a-input>
                                </template>
                                <template v-else>
                                    <span :class="rowIndex == hightIndex ? 'hight' : ''">{{ record.key }}</span>
                                </template>
                            </template>
                        </a-table-column>

                        <a-table-column v-for="(itm, index) in langKey" :key="index" :title="itm.name" align="center">
                            <template #cell="{ record, column, rowIndex }">
                                <a-input :key="'input-lang-' + index" v-model="record[itm.file_name]"
                                    :placeholder="`请输入对应的${itm.name}`" allow-clear />
                            </template>
                        </a-table-column>
                    </template>

                </a-table>
            </a-scrollbar>
            <a-pagination class="pagination" @change="pageChange" @page-size-change="limitChange"
                :page-size-options="[20, 50, 100]" :total="queryParams.total" :show-total="true"
                :current="queryParams.page" :page-size="queryParams.limit" :size="size" show-total show-jumper
                show-page-size />
            <div class="btns">
                <s-apace>
                    <div class="up_box">
                        <icon-caret-up class="up" @click="selfScroll('up')" />
                        <icon-caret-down class="up" @click="selfScroll('down')" />
                    </div>
                </s-apace>
            </div>
        </a-spin>

        <template #footer>
            <div class="footer">
                <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
                    <a-form-item label="版本号" field="version">
                        <a-input v-model="formData.version" placeholder="选填, 不填自动迭代版本"></a-input>
                    </a-form-item>
                    <a-form-item label="操作密码" field="admin_pay_password">
                        <a-input-password v-model="formData.admin_pay_password" placeholder="请输入" />
                    </a-form-item>
                    <a-form-item label="谷歌验证码" field="google_code">
                        <a-input v-model="formData.google_code" placeholder="请输入" />
                    </a-form-item>
                    <a-form-item>
                        <a-space>
                            <a-button type="primary" @click="submit" :loading="loading">提交</a-button>
                            <a-button @click="close">取消</a-button>
                        </a-space>
                    </a-form-item>
                </a-form>
            </div>
        </template>
    </component>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from "vue";
import { Message } from "@arco-design/web-vue";
import languageApi from '@/api/system/system'
import * as XLSX from 'xlsx';
import { throttle } from "lodash";
import tool from "@/utils/tool";
import ENUMS from "@/utils/enums";
const queryParams = reactive({
    total: 0,
    limit: 20,
    page: 1,
})
const formRef = ref();
const tableRef = ref();
const emit = defineEmits(["success"]);

// 引用定义
const searchForm = ref({
    client: "",
    keyword: ""
});
const formData = reactive({
    admin_pay_password: "",
    google_code: "",
    version: "",
    client: '',
    lang_data: [],
});
const tableData = ref([]);
const allTableData = ref([])
const langKey = ref([]);
const visible = ref(false);
const loading = ref(false);
const spinLoading = ref(false);
const scrollRef = ref();
const isSearching = ref(false);
const rules = ref({
    admin_pay_password: [{ required: true, message: "请输入" }],
    google_code: [{ required: true, message: "请输入" }]
});
const currentPageData = computed(() => {
    const start = (queryParams.page - 1) * queryParams.limit;
    const end = start + queryParams.limit;
    queryParams.total = tableData.value.length
    return tableData.value.slice(start, end);
});
watch(() => queryParams.page, () => {
    if (!isSearching.value) {
        hightIndex.value = null;
    }
    isSearching.value = false;
});

// 监听每页条数变化
watch(() => queryParams.limit, () => {
    hightIndex.value = null;
});
const pageChange = (page) => {
    queryParams.page = page;
};
const limitChange = (limit) => {
    queryParams.page = 1;
    queryParams.limit = limit;
    // getData();
};
const getData = async () => {
    spinLoading.value = true;
    try {
        const { data } = await languageApi.updateLanguageList(searchForm.value);
        langKey.value = data.lang_name;
        allTableData.value = data.data
        tableData.value = data.data;
        queryParams.total = tableData.value.length;
        spinLoading.value = false;
    } catch {
    } finally {
        spinLoading.value = false;
    }
};
const hightIndex = ref()
const getBlur = (txt) => {
    if (txt) {
        const exists = tableData.value.some(item => { item.key == txt });
        if (exists) {
            Message.warning(`key为 ${txt} 的多语言已存在！`)
            return false
        }
    }
}
const search = () => {
    if (!searchForm.value.keyword) {
        Message.warning("请输入关键字");
        return false;
    }
    const targetRow = allTableData.value.find((itm, idx) => itm.key === searchForm.value.keyword);

    if (targetRow) {
        const targetIndexInAllData = allTableData.value.indexOf(targetRow);  // 在全量数据中的索引
        const targetPage = Math.floor(targetIndexInAllData / queryParams.limit) + 1;
        isSearching.value = true;
        queryParams.page = targetPage;
        const startIndex = (targetPage - 1) * queryParams.limit;
        const targetIndexInPage = targetIndexInAllData - startIndex;  // 在当前分页数据中的索引
        hightIndex.value = targetIndexInPage;

        scrollRef.value.scrollTo({ top: targetIndexInPage * 50 });

    } else {
        Message.warning("未找到匹配结果");
    }
};

// 打开弹框
const open = async (data) => {
    searchForm.value.client = data;
    formData.client = data
    getData();
    visible.value = true;
};

// 1.5秒內只允許點一次
const addKey = throttle(async () => {
    let value = { key: "", type: "add", };
    langKey.value.forEach((itm) => {
        value[itm.file_name] = "";
    });
    tableData.value.push(value);
    const totalPages = Math.ceil(tableData.value.length / queryParams.limit);
    queryParams.page = totalPages;
    const remian = tableData.value.length % queryParams.limit
    await nextTick(() => {
        scrollRef.value.scrollTo({ top: remian * 50 });
    });
}, 1500);

const deleteColumn = (index) => {
    // 在所有的数组中的index为379 所以刪除的應该是xx.splice(379,1)
    tableData.value.splice(queryParams.limit * (queryParams.page - 1) + index, 1)
    allTableData.value.splice(queryParams.limit * (queryParams.page - 1) + index, 1)
    // console.log('1',currentPageData.value);
    // console.log('2',tableData.value);
    // console.log('3',allTableData.value);

};

const selfScroll = (type) => {
    if (type === "up") {
        scrollRef.value?.scrollTo({ top: 0 });
    } else {
        scrollRef.value?.scrollTo({ top: tableData.value.length * 50 });
    }
};

const refreshSql = throttle(async () => {
    spinLoading.value = true
    try {
        const { data } = await languageApi.sqlLanguage({ client: searchForm.value.client })
        queryParams.page = 1
        getData()
        Message.success('导入成功')
    } finally {
        spinLoading.value = true
    }
}, 3000)
const exportExcel = throttle(async () => {
    const downloadUrl = `${import.meta.env.VITE_APP_BASE_URL}/p5wznrna/lang/export?fro_source=1&client=${searchForm.value.client}&keyword=${searchForm.value.keyword}`
    window.location.href = downloadUrl
}, 3000)
const fileList=ref([])
const uploadExcel = (e) => {
    let isTrue=true
    const files = e[0].file
    if (files) {
        const reader = new FileReader();

        reader.onload = (event) => {
            const target = event.target.result; // 获取文件内容
            const workbook = XLSX.read(target, { type: 'binary' }); // 解析 Excel 文件
            const sheetName = workbook.SheetNames[0]; // 获取第一个工作表
            const worksheet = workbook.Sheets[sheetName]; // 获取该工作表内容
            var keyName = ['key']; // 根据你的需要更改这些名称
            var langName = ['key'];
            for (var i = 0; i < langKey.value.length; i++) {
                keyName.push(langKey.value[i].file_name)
                langName.push(langKey.value[i].name)
            }
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            for (var a = 0; a < jsonData[0].length; a++) {
                if (jsonData[0][a] && langName.indexOf(jsonData[0][a]) < 0) {
                    console.log(jsonData[0][a])
                    console.log(langName)
                    isTrue = false;
                    break;
                }
            }
            if (!isTrue) {
              fileList.value=[]
              return  Message.error('表头：语言' + jsonData[0][a] + '不存在')          
            }
            let data = []
            var headers = jsonData.shift(), row, header, value; // 获取并移除第一行作为表头
            for (var i = 0; i < jsonData.length; i++) {
                // key值即不存在
                if (jsonData[i][0]) {
                    row = {};
                    for (var j = 0; j < headers.length; j++) {
                        header = headers[j];
                        value = jsonData[i][j];
                        row[keyName[j]] = value; // 根据需要设置别名，这里使用 '别名' + (j+1)

                    }
                    data.push(row);
                }
            }
            if (data.length < 1) {
                return Message.msg('未读取到数据,请重新选择文件');
            }
            console.log('data', data);
            spinLoading.value = true
            tableData.value = []
            tableData.value = data
            Message.success('导入成功，请检查')
            spinLoading.value = false
            fileList.value=[]
        };

        reader.readAsBinaryString(files); // 读取文件内容
    } else {
        Message.error('无法解析Excel, 请重試')
    }
}
// 数据保存
const submit = throttle(async () => {
    const validate = await formRef.value?.validate();
    if (!validate) {
        loading.value = true;
        try {
            formData.lang_data = allTableData.value
            formData.lang_data = JSON.stringify(allTableData.value)
            const { data } = await languageApi.updateLanguage(formData)
            Message.success('保存成功')
            queryParams.page = 1
            formData.admin_pay_password = ''
            formData.google_code = ''
            formData.lang_data = []
            formData.version = ''
            getData()
        } finally {
            loading.value = false
        }
    }
}, 100)

// 关闭弹窗
const close = () => {
    formRef.value.resetFields();
    visible.value = false;
    hightIndex.value = null
};

defineExpose({ open });
</script>

<style scoped lang="less">
.row_column {
    position: fixed;
    top: 10px;
    background-color: teal;
}

.row_col {
    width: 100%;
    display: flex;
    justify-content: flex-end;
}

.btns {
    position: fixed;
    bottom: 50px;
    right: 40px;
}

.up_box {
    display: flex;
    flex-direction: column;

    .up {
        width: 30px;
        cursor: pointer;
        border-radius: 50%;
        background-color: #fff;
        height: 30px;
        margin-bottom: 20px;
    }

    .up:hover {
        color: orangered;
    }
}

.hight {
    color: #fff;
    background-color: #f39c12;
}

.pagination {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>